﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;

namespace Sharpener.Analysis
{
	public class MethodControlFlowGraph
	{
		public MethodDefinition Method { get; private set; }
		List<BasicBlock> blocks;

		public BasicBlock EntryBlock { get; private set; }
		public BasicBlock ExitBlock { get; private set; }

		public MethodControlFlowGraph( MethodDefinition methodDefinition )
		{
			if(!methodDefinition.HasBody)
				throw new Exception("Cannot create a control flow graph for a method with no body.");

			Method = methodDefinition;
			blocks = BasicBlock.ScanForBlocks(Method.Body.Instructions);

			constructGraph();
		}

		private void constructGraph()
		{
			var lookup = createLookupDictionary();
			
			//go!
			EntryBlock = blocks[0];
			ExitBlock = blocks[blocks.Count - 1];

			int blockIndex = 0;

			foreach(var block in blocks)
			{
				var tail = block.Tail;
				BasicBlock successor = null;

				switch(tail.OpCode.FlowControl)
				{
					case FlowControl.Next:
						break;
					case FlowControl.Branch:
						successor = lookup[tail.Operand as Instruction];
						block.Successors.Add(successor);
						successor.Predecessors.Add(block);
						break;
					case FlowControl.Cond_Branch:
						successor = lookup[tail.Operand as Instruction];
						block.Successors.Add(successor);
						successor.Predecessors.Add(block);
						//if branch not taken successor exists, add it too
						if(blockIndex < blocks.Count - 1)
						{
							var suc = blocks[blockIndex + 1];
							block.Successors.Add(suc);
							suc.Predecessors.Add(block);
						}
						break;
					case FlowControl.Return:
						break;
				
					default:
						throw new Exception("This flow control is not currently handled.");
				}
				
				blockIndex++;
			}
		}

		private Dictionary<Instruction,BasicBlock> createLookupDictionary()
		{
			var blockDictionary = new Dictionary<Instruction, BasicBlock>(blocks.Count);

			foreach(var block in blocks)
			{
				Debug.Print(block.Head.ToString());
				blockDictionary.Add(block.Head, block);
			}

			return blockDictionary;
		}
	}
}